package com.xz.purchase.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.log.domain.OperationLog;
import com.xz.log.service.IOperationLogService;
import com.xz.product.domain.Product;
import com.xz.product.service.IProductService;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.dto.PurchasePriceDto;
import com.xz.purchase.vo.PurchasePriceImportVo;
import com.xz.supplier.domain.Supplier;
import com.xz.supplier.service.ISupplierService;
import common.ECDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.purchase.mapper.PurchasePriceMapper;
import com.xz.purchase.domain.PurchasePrice;
import com.xz.purchase.service.IPurchasePriceService;
import org.springframework.util.CollectionUtils;

/**
 * 进货价Service业务层处理
 *
 * @author xz
 * @date 2024-01-08
 */
@Service
public class PurchasePriceServiceImpl extends ServiceImpl<PurchasePriceMapper, PurchasePrice> implements IPurchasePriceService {
    @Autowired
    private PurchasePriceMapper purchasePriceMapper;
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private IProductService iProductService;
    @Autowired
    private ISupplierService iSupplierService;

    /**
     * 查询进货价
     *
     * @param id 进货价主键
     * @return 进货价
     */
    @Override
    public PurchasePrice selectPurchasePriceById(Long id) {
        return purchasePriceMapper.selectPurchasePriceById(id);
    }

    /**
     * 查询进货价列表
     *
     * @param purchasePrice 进货价
     * @return 进货价
     */
    @Override
    public List<PurchasePriceDto> selectPurchasePriceList(PurchasePrice purchasePrice) {
        return purchasePriceMapper.selectPurchasePriceList(purchasePrice);
    }

    /**
     * 新增进货价
     *
     * @param purchasePrice 进货价
     * @return 结果
     */
    @Override
    public BigDecimal insertPurchasePrice(PurchasePrice purchasePrice) {
        //校验是否存在对应商品价格
        PurchasePrice price = purchasePriceMapper.selectPurchasePrice(purchasePrice);
        if(Objects.isNull(price)){
            purchasePrice.setCreateTime(DateUtils.getNowDate());
            purchasePrice.setCreateBy(SecurityUtils.getUserId());
            purchasePrice.setPurchasePrice(BigDecimal.ZERO);
            purchasePrice.setDeptId(SecurityUtils.getDeptId());
            int insertPurchasePrice = purchasePriceMapper.insertPurchasePrice(purchasePrice);
            if(insertPurchasePrice>0){
                operationLogService.insertOperationLog(
                        new OperationLog(purchasePrice.getId()+"",2,purchasePrice.getTenantId(),
                                SecurityUtils.getUserId(),SecurityUtils.getUsername(), ECDateUtils.formatDate(new Date(),"yyyy-MM-dd") +"，新增，进货单价"+purchasePrice.getPurchasePrice()+"元"));
            }
            return BigDecimal.ZERO;
        }
        return price.getPurchasePrice() ==null?BigDecimal.ZERO:price.getPurchasePrice();
    }

    /**
     * 修改进货价
     *
     * @param purchasePrice 进货价
     * @return 结果
     */
    @Override
    public AjaxResult updatePurchasePrice(PurchasePrice purchasePrice) {
        PurchasePrice price = purchasePriceMapper.selectPurchasePriceById(purchasePrice.getId());
        if(Objects.isNull(price)){
            return AjaxResult.success("进货价修改失败");
        }
        purchasePrice.setUpdateTime(DateUtils.getNowDate());
        purchasePrice.setUpdateBy(SecurityUtils.getUserId());
        int updatePurchasePrice = purchasePriceMapper.updatePurchasePrice(purchasePrice);
        if(updatePurchasePrice>0){
            operationLogService.insertOperationLog(
                    new OperationLog(price.getId()+"",2,price.getTenantId(),
                            SecurityUtils.getUserId(),SecurityUtils.getUsername(), ECDateUtils.formatDate(new Date(),"yyyy-MM-dd") +"，修改，采购单价"+purchasePrice.getPurchasePrice()+"元"));
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 导入进货单价
     * @param list
     * @return
     */
    @Override
    public AjaxResult importExcel(List<PurchasePriceImportVo> list) {
        List<PurchasePrice> insertPurchasePrices=new ArrayList<>();
        List<PurchasePrice> updatePurchasePrices=new ArrayList<>();
        List<OperationLog> operationLogList=new ArrayList<>();
        for(PurchasePriceImportVo purchasePriceImportVo:list){
            PurchasePrice price=new PurchasePrice();
            //获取商品信息
            Product purchaseInfo = iProductService.getProductInfo(purchasePriceImportVo.getProductEncoded());
            if(Objects.isNull(purchaseInfo)){
                return AjaxResult.error("导入失败,商品编号："+purchasePriceImportVo.getProductEncoded()+"，不存在");
            }
            price.setProductId(purchaseInfo.getId());
            //获取供应商信息
            Supplier supplierInfo = iSupplierService.getSupplierInfo(purchasePriceImportVo.getSupplierName());
            if(Objects.isNull(supplierInfo)){
                return AjaxResult.error("导入失败,供应商："+purchasePriceImportVo.getSupplierName()+"，不存在");
            }
            price.setSupplierId(supplierInfo.getId());
            if(purchasePriceImportVo.getPurchasePrice()==null){
                return AjaxResult.error("导入失败,请填写正确的金额");
            }
            PurchasePrice finalPrice = price;
            long count = insertPurchasePrices.stream().filter(i -> i.getProductId().equals(finalPrice.getId()) && i.getSupplierId().equals(finalPrice.getSupplierId())).count();
            if(count>0){
                continue;
            }
            price.setDeptId(SecurityUtils.getDeptId());
            //通过商品和供应商获取是否已经存在进货价格
            List<PurchasePrice> selectList = baseMapper.selectList(new QueryWrapper<PurchasePrice>().eq("supplier_id", supplierInfo.getId()).eq("product_id", purchaseInfo.getId()));
            if(CollectionUtils.isEmpty(selectList)) {
                price.setCreateTime(DateUtils.getNowDate());
                price.setCreateBy(SecurityUtils.getUserId());
                price.setUpdateTime(DateUtils.getNowDate());
                price.setUpdateBy(SecurityUtils.getUserId());
                price.setTenantId(SecurityUtils.getLoginUser().getTenantId());
                price.setPurchasePrice(purchasePriceImportVo.getPurchasePrice());
                insertPurchasePrices.add(price);
            }else{
                price=selectList.get(0);
                price.setUpdateTime(DateUtils.getNowDate());
                price.setUpdateBy(SecurityUtils.getUserId());
                price.setPurchasePrice(purchasePriceImportVo.getPurchasePrice());
                updatePurchasePrices.add(price);
            }



            /*Pattern pattern = Pattern.compile("[0-9]*\\.?[0-9]+");
            Matcher isNum = pattern.matcher();
            if (!isNum.matches()) {
                return false;
            }*/
        }
        if(!CollectionUtils.isEmpty(insertPurchasePrices)){
            boolean saveBatch = this.saveBatch(insertPurchasePrices);
            if(saveBatch){
                insertPurchasePrices.stream().forEach(price->{
                    OperationLog operationLog= new OperationLog(price.getId()+"",2,price.getTenantId(),
                            SecurityUtils.getUserId(),SecurityUtils.getUsername(), ECDateUtils.formatDate(new Date(),"yyyy-MM-dd") +"，新增，采购单价"+price.getPurchasePrice()+"元");
                    operationLogList.add(operationLog);
                });
            }
        }
        if(!CollectionUtils.isEmpty(updatePurchasePrices)){
            boolean saveBatch = this.updateBatchById(updatePurchasePrices);
            if(saveBatch) {
                updatePurchasePrices.stream().forEach(price -> {
                    OperationLog operationLog = new OperationLog(price.getId() + "", 2, price.getTenantId(),
                            SecurityUtils.getUserId(), SecurityUtils.getUsername(), ECDateUtils.formatDate(new Date(), "yyyy-MM-dd") + "，修改，采购单价" + price.getPurchasePrice() + "元");
                    operationLogList.add(operationLog);
                });
            }
        }
        if(!CollectionUtils.isEmpty(operationLogList)){
            operationLogService.saveBatch(operationLogList);
            return AjaxResult.success("导入成功");
        }
        return AjaxResult.error("导入失败");
    }

    /**
     * 批量删除进货价
     *
     * @param ids 需要删除的进货价主键
     * @return 结果
     */
    @Override
    public int deletePurchasePriceByIds(Long[] ids) {
        return purchasePriceMapper.deletePurchasePriceByIds(ids);
    }

    /**
     * 删除进货价信息
     *
     * @param id 进货价主键
     * @return 结果
     */
    @Override
    public int deletePurchasePriceById(Long id) {
        return purchasePriceMapper.deletePurchasePriceById(id);
    }
}
